import * as THREE from 'three';
import { picData } from '@/assets/data';
import EventBus from '@/assets/bus';

export function loaderRoam(app) {
  createIconGroup(app);

  // 鼠标移动事件
  app.initRaycaster(onMouseMove, app.rayModel, 'mousemove');

  // 鼠标点击事件
  app.initRaycaster(onClick, app.rayModel, 'click');
}

function onClick(selectObj, app) {
  if (app.controls.isClickLock) {
    return;
  }

  if (selectObj?.object?.name === '地板') {
    const point = selectObj.point;
    console.log(point);
    let position,
      controls,
      isContains = false;
    for (const key in app.helperBox) {
      if (Object.hasOwnProperty.call(app.helperBox, key)) {
        const obj = app.helperBox[key];
        if (obj.box.containsPoint(point)) {
          isContains = true;
          position = obj.position;
          controls = obj.controls;
        }
      }
    }

    if (!isContains) {
      const subVec3 = app.camera.position.clone().sub(app.controls.target.clone());
      position = [point.x, app.camera.position.y, point.z];
      controls = [point.x - subVec3.x, app.camera.position.y - subVec3.y, point.z - subVec3.z];
    }

    app.flyTo({
      position,
      controls,
      done: () => {
        app.iconGroup.visible = true;
      },
      start: () => {
        app.iconGroup.visible = false;
      }
    });
  }

  if (selectObj?.object?.name.indexOf('pic') > -1) {
    const model = selectObj.object;
    const obj = picData[model.name];
    if (obj) {
     EventBus.$emit('changeDialog', obj);
    }
  }
}

function onMouseMove(selectObj, app) {
  if (selectObj?.object?.name === '地板') {
    const point = selectObj.point;
    app.iconGroup.position.copy(point.add(new THREE.Vector3(0, 0.01, 0)));
    app.iconGroup.visible = true;
  } else {
    app.iconGroup.visible = false;
  }
}

function createIconGroup(app) {
  const group = new THREE.Group();

  const circleGeometry = new THREE.CircleGeometry(0.2, 32);
  const circleMaterial = new THREE.MeshBasicMaterial({
    color: '#fff',
    transparent: true,
    opacity: 0.2
  });
  const circle = new THREE.Mesh(circleGeometry, circleMaterial);
  circle.rotateX(-0.5 * Math.PI);
  group.add(circle);

  const ringGeometry = new THREE.RingGeometry(0.22, 0.2, 32);
  const ringMaterial = new THREE.MeshBasicMaterial({
    color: '#fff',
    transparent: true,
    opacity: 0.8,
    side: THREE.DoubleSide
  });
  const ring = new THREE.Mesh(ringGeometry, ringMaterial);
  ring.rotateX(-0.5 * Math.PI);
  group.add(ring);

  group.position.set(0.63, 1, -18.18);
  group.visible = false;
  app.iconGroup = group;
  app.scene.add(group);
}
